package pyip.lib.mixtool.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketServer {

	public static void main(String[] args) {
		SocketServer server = new SocketServer();
		server.start();
	}

	private void start() {
		ServerSocket serverSocket = null;
		
		try {
			try {
				serverSocket = new ServerSocket(1000);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			int totalConnect = 0;
			while (true) {
				Socket socket = null;
				PrintWriter writer = null;
				BufferedReader reader = null;
				try {
					socket = serverSocket.accept();
					totalConnect++;
					System.out.println("totalConnect: " + totalConnect);
					
					writer = new PrintWriter(socket.getOutputStream());
					String sendline = "i am server, threadNum " + Thread.currentThread().getId() + "";
					System.out.println("server send: " + sendline);
					writer.write(sendline);
					writer.flush();

					reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					String line = reader.readLine();
					System.out.println("server receive: " + line);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (null != reader) {
						try {
							reader.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					if (null != writer) {
						// TODO no exception ??
						writer.close();
					}
					if (null != socket) {
						try {
							socket.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		} finally {
			if (null != serverSocket) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
